package com.zhengbing.tj.controller;

import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.utils.CaptchaUtil;
import com.zhengbing.tj.common.RequestContextUtil;
import com.zhengbing.tj.common.ApiResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.ApiResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 验证码接口控制器，提供验证码生成与校验功能
 *
 * @author zhengbing
 * @date 2025-07-16
 */
@Api(tags = "验证码管理", description = "提供验证码生成与校验功能")
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    /**
     * 生成输入验证码图片
     * 生成5位数的字符验证码并输出图片流
     */
    @ApiOperation(value = "生成验证码图片", notes = "生成5位数的字符验证码并输出图片流")
    @ApiResponses({
        @ApiResponse(code = 200, message = "生成成功")
    })
    @GetMapping("/input")
    public void inputCaptcha() throws Exception {
        // 生成5位数的字符验证码
        SpecCaptcha captcha = new SpecCaptcha(150, 40, 5);
        // 保存验证码到session
        RequestContextUtil.getRequest().getSession().setAttribute("captcha", captcha.text());
        // 输出图片流
        CaptchaUtil.out(captcha, RequestContextUtil.getRequest(), RequestContextUtil.getResponse());
    }

    /**
     * 校验验证码
     * 校验用户输入的验证码是否正确
     *
     * @param body 包含验证码的请求体
     * @return 校验结果
     */
    @ApiOperation(value = "校验验证码", notes = "校验用户输入的验证码是否正确")
    @ApiResponses({
        @ApiResponse(code = 200, message = "校验成功", response = ApiResult.class),
        @ApiResponse(code = 400, message = "验证码错误")
    })
    @PostMapping("/verify")
    public ApiResult<Map<String, Object>> verifyCaptcha(@ApiParam(value = "包含验证码的请求体", required = true) @RequestBody Map<String, String> body) {
        String userInput = body.get("code");
        String sessionCode = (String) RequestContextUtil.getRequest().getSession().getAttribute("captcha");
        Map<String, Object> result = new HashMap<>();
        if (sessionCode != null && sessionCode.equalsIgnoreCase(userInput)) {
            result.put("success", true);
            result.put("message", "验证码正确");
            return ApiResult.success(result);
        } else {
            result.put("success", false);
            result.put("message", "验证码错误");
            return ApiResult.error(400, "验证码错误", result);
        }
    }
}